<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\Apply as ApplyModel;
use app\common\model\ApplyPic;
class Apply extends Api
{
    public function index(){
        
        $params = paramForm();
        if(isset($params['action'])){
            switch ($params['action']){
                case 'add':
                    $this->save($params);
                    break;
            }
        }
        
        $one = ApplyModel::get(['user_id'=>$this->getUserId()]);
        success($one);
    }
    
    public function save($params){
        $apply = new ApplyModel();
        $params['user_id'] = $this->getUserId();
        $rt = $apply->allowField(true)->save($params);
    
        $pics = $params['pics'];
        $wxDevConfig = config('thirdaccount.WeChatDeveloper');
        try {
            $picArr = [];
            $picModel = new ApplyPic();
        
            foreach ($pics as $pic){
            
                // 实例接口
                $wechat = new \WeChat\Media($wxDevConfig);
                // 保存到本地
                $result = $wechat->get($pic);
            
                // 处理执行的结果
                if($result===FALSE){
                    // 接口失败的处理
                    error('获取微信临时文件资源失败');
                }else{
                    $filename = uniqid().'.jpg';            //定义图片名字及格式
                    $tempFile = saveFile($filename,$result);
                    $file = new \think\File($tempFile);
                    if($file){
                        $oss_url = $this->uploadToAlyun($file);
                        $picArr[] = ['apply_id' => $apply->id,'url'=>$oss_url];
                    }else{
                        error('上传文件缺失');
                    }
                
                }
            }
            $picModel->saveAll($picArr);
        
        } catch (Exception $e) {
            // 出错啦，处理下吧
            echo  error($e->getMessage());
        
        }
        
        
        if($rt){
            success('提交申请成功');
        }else{
            error('提交申请失败');
        }
        
    }
    
}
